﻿using System;
using DMS.BaseClass;
using DMS.Business.Modules.SupplierManagement;
using DMS.Business.Utility;
using DMS.Business.Modules.Organization;

namespace DMS.Web.Common.Controls
{
    public partial class ModifyPasswordForm : ContentFormControlBase
    {
        #region 界面属性
        private bool _CheckOldPwd = true;
        public bool CheckOldPwd
        {
            get
            {
                return this._CheckOldPwd;
            }
            set
            {
                this._CheckOldPwd = value;
            }
        }
        #endregion

        #region 界面事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.InitCtrls();
            }
        }
        #endregion

        #region 界面逻辑
        private void InitCtrls()
        {
            this.trOldPwd.Visible = this.CheckOldPwd;
        }

        public void Save()
        {
            if (!this.Page.IsValid)
            {
                return;
            }

            // 当前用户
            AuthenticationUser contextUser = SystemContext.Current.LoginAuthUser;
            AuthenticationUser targetUser = contextUser;
            
            // 获取当前编辑成员
            if (!string.IsNullOrEmpty(Request["ActorID"])
                && !string.IsNullOrEmpty(Request["Type"])
                && (contextUser.IsSystemManager || contextUser.IsMaterialManager))
            {
                string id = Request["ActorID"].ToString();
                ActorTypes type = (ActorTypes)Enum.Parse(typeof(ActorTypes), Request["Type"].ToString());
                switch (type)
                {
                    case ActorTypes.SupplierAccount:
                        Supplier supplier = SupplierHelper.GetSupplierByID(id);
                        targetUser = supplier.DefaultAccount;
                        break;
                    case ActorTypes.User:
                        targetUser = UserHelper.GetUserByID(id);
                        break;
                }
            }

            // 检查旧密码
            if (!this.Check(targetUser))
            {
                this.txtOldPWD.Text = string.Empty;
                ClientHelper.Instance.Alert("输入的旧密码不正确，请重新输入！");
                return;
            }

            // 修改密码
            targetUser.ResetPassword(this.txtNewPWD.Text.Trim());
            ClientHelper.Instance.Alert("修改成功！");
        }

        public bool Check(AuthenticationUser aUser)
        {
            if (!this.CheckOldPwd)
            {
                return true;
            }

            return aUser.CheckPassword(this.txtOldPWD.Text);
        }
        #endregion
    }
}